const path = require('path');
const fs = require('fs');
const escapeStringRegexp = require('escape-string-regexp');

const util = require('./util');

module.exports = {
  isRelativePath (ref) {
    return /^(\\\.(\\\.)?\/)/.test(escapeStringRegexp(ref));
  },

  getAliasPath (ref, pathAlias = {}) {
    let result;
    for (let key in pathAlias) {
      let reg = new RegExp(`^${escapeStringRegexp(key)}`);
      if (reg.test(ref)) {
        result = {
          key,
          value: pathAlias[key]
        };
      }
    }
    return result;
  },

  relativePathHandler (source, ref, config) {
    let _ref = path.resolve(path.dirname(source), ref);
    return this.filenameHandler(_ref, config);
  },

  aliasPathHandler (ref, alias, extensions) {
    let reg = new RegExp(`^${escapeStringRegexp(alias.key)}`);
    let _ref = ref.replace(reg, alias.value);
    return this.filenameHandler(_ref, extensions);
  },

  filenameHandler (ref, extensions = []) {
    let result;
    if (util.isDirectory(ref)) {
      let files = fs.readdirSync(ref);
      files.some(file => {
        let info = path.parse(`${ref}/${file}`);
        if (info.name === 'index' && extensions.indexOf(info.ext) !== -1) {
          result = `${ref}/${file}`;
          return true;
        } else {
          return false;
        }
      });
    } else {
      let info = path.parse(ref);
      let files = fs.readdirSync(info.dir);
      files.some(file => {
        if (file.split('.')[0] === path.basename(ref) && extensions.indexOf(path.extname(file)) !== -1) {
          result = `${info.dir}/${file}`;
          return true;
        } else {
          return false;
        }
      });
    }
    return result;
  },

  parsePath (source, ref, config) {
    let alias;
    let pathAlias = config.pathAlias || {};
    let extensions = config.extensions || [];
    if (this.isRelativePath(ref)) {
      return this.relativePathHandler(source, ref, extensions);
    } else if (alias = this.getAliasPath(ref, pathAlias)) {
      return this.aliasPathHandler(ref, alias, extensions);
    }
  }
}
